package utils;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class UploadImageUtils {


    public static void uploadImageToServer(String localFilePath, String host, String remoteDirectory, String username, String password) {
        JSch jSch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            // SSH连接
            session = jSch.getSession(username, host, 22);
            session.setPassword(password);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            // SFTP通道
            Channel channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;

            File localFile = new File(localFilePath);
            FileInputStream fis = new FileInputStream(localFile);

            // 获取文件扩展名
//            String fileExtension = localFile.getName().substring(localFile.getName().lastIndexOf("."));
            String remoteFileName = localFile.getName();

            // 上传文件
            channelSftp.put(fis, remoteDirectory + remoteFileName);
            fis.close();

//            System.out.println("文件上传成功！");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
